<template>
	<a-modal v-bind="option" class="select-house">
		<div class="select-house-flex">
			<vxe-grid v-if="visible" ref="grid" class="table-class" v-bind="houseListTableOption">
				<template v-if="getCheckeds().length" #top>
					<vxe-toolbar class="table-selected-wrapper" perfect>
						<template #buttons>
							<span>
								已选择
								<span v-color="{color: 'primary'}">{{ getCheckeds().length }}</span>
								条
							</span>
						</template>
					</vxe-toolbar>
				</template>
				<template #toolbar>
					<div class="margin-10">
						<a-typography-text strong>
							<blockquote>房源列表</blockquote>
						</a-typography-text>
						<a-input-group compact class="display-flex">
							<a-select
								v-model:value="search.houseType"
								:options="houseType"
								placeholder="请选择类型"
								@select="getHouseList"
								style="width: 115px" />

							<a-input-search
								size="default"
								v-model:value.trim="search.like"
								:allow-clear="true"
								placeholder="请输入房源地址"
								enter-button
								@search="getHouseList" />
						</a-input-group>
					</div>
				</template>
			</vxe-grid>
			<div class="button-group">
				<a-button type="primary" class="margin-bottom-20" @click="select">
					加入
					<right-outlined />
				</a-button>
				<a-button type="primary" @click="remove">
					<left-outlined />
					移除
				</a-button>
			</div>
			<vxe-grid ref="selectedTable" class="table-class" v-bind="selectedOption" :data="standbyList">
				<template v-if="getRemoves().length" #top>
					<vxe-toolbar class="table-selected-wrapper" perfect>
						<template #buttons>
							<span>
								已选择
								<span v-color="{color: 'primary'}">{{ getRemoves().length }}</span>
								条
							</span>
						</template>
					</vxe-toolbar>
				</template>
				<template #toolbar>
					<div class="margin-10">
						<a-typography-text strong>
							<blockquote>已选中列表</blockquote>
						</a-typography-text>
						<a-input-search
							v-model:value.trim="searchLike"
							:allow-clear="true"
							placeholder="请输入房源地址"
							enter-button
							@search="searchLikeClick" />
					</div>
				</template>
				<template #bottom>
					<vxe-toolbar>
						<template #tools>共选择{{ echoSelectedList.length }}条数据</template>
					</vxe-toolbar>
				</template>
			</vxe-grid>
		</div>
		<template #footer>
			<a-button key="submit" :loading="loadings.save" type="primary" @click="submit">提交已选中房间</a-button>
		</template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {reactive, ref, toRef, watch, useAttrs} from 'vue'
	import {VxeGridInstance, VxeGridProps} from 'vxe-table'
	import {getVacancyHouseList} from '@/api/contract'
	import XEUtils from 'xe-utils'
	import {pagerConfig, proxyConfigProps} from 'yuxin-base/src/utils/vxe-table'
	import {message} from 'ant-design-vue'
	import {LeftOutlined, RightOutlined} from '@ant-design/icons-vue'

	const props = defineProps<{
		visible: boolean
		roomSelected?: any[]
	}>()

	const search = reactive({
		houseType: 3,
		like: null
	})

	const loadings = reactive({
		calc: false,
		save: false
	})

	const houseType = [
		{
			label: '集中式',
			value: 3
		},
		{
			label: '分散式',
			value: 0
		}
	]
	const validateFee = (contractDecision,houseDetailList) =>{
		if(!contractDecision) return
		const errorList = [
		]
		 houseDetailList.map(houseDetail=>{
			 const {communityPropertyPrice,propertyPrice,depositPrice,address} = houseDetail
			 console.log(contractDecision.disabledeposit,'111');
			const itemErrorList = []
			 const validatePorperty = contractDecision.shiftProperty && contractDecision.shiftPropertyType === 1
			 const validateDeposit = contractDecision.disabledeposit
			 const validatePorpertyByArea = contractDecision.shiftProperty && contractDecision.shiftPropertyType === 2
			 if(validatePorperty && !propertyPrice) {
				itemErrorList.push({name:'房型物业费'})
			 }
			 if(validatePorpertyByArea && !communityPropertyPrice) {
				itemErrorList.push({name:'物业费单价'})
			 }
			 if(validateDeposit && !depositPrice) {
				itemErrorList.push({name:'房型押金'})
			 }
			 itemErrorList.length && errorList.push({name:`${address}：未配置${itemErrorList.map(e=>e.name).join('、')}`})
		})
			const nameStr = errorList.map(e=>e.name).join('；')
			errorList.length && message.error(`${nameStr}，无法操作，请先编辑房源进行配置`)
		return !errorList.length
	}

	const emits = defineEmits(['update:visible', 'success'])
	const option = reactive({
		width: '80vw',
		title: '选择房间',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			echoSelectedList.value = []
			search.houseType = 3
			search.like = null
			searchLike.value = null
			emits('update:visible', false)
		}
	})

	const grid = ref<VxeGridInstance>()
	const houseListTableOption = reactive<VxeGridProps>({
		height: 'auto',
		size: 'medium',
		showOverflow: true,
		rowConfig: {
			isHover: true,
			keyField: 'id'
		},
		checkboxConfig: {
			reserve: true,
			trigger: 'row',
			checkMethod: ({row}) => {
				return !echoSelectedList.value.map(o => o.id).includes(row.id)
			}
		},
		columns: [
			{
				width: 60,
				align: 'center',
				fixed: 'left',
				type: 'checkbox'
			},
			{
				title: '房源地址',
				minWidth: 400,
				align: 'left',
				resizable: true,
				field: 'address'
			},
			{
				title: '租金(元)',
				minWidth: 100,
				align: 'right',
				field: 'actualPrice'
			},
			{
				title: '押金(元)',
				minWidth: 100,
				align: 'right',
				field: 'actualPrice'
			}
		],
		pagerConfig: {
			...pagerConfig,
			pageSize: 100
		},
		proxyConfig: {
			props: proxyConfigProps,
			ajax: {
				query({page: {currentPage: current, pageSize: size}}) {
					return getVacancyHouseList({...search, current, size})
				}
			}
		}
	})

	const searchLike = ref<any>(null)
	const standbyList = ref<any>([])
	const echoSelectedList = ref<any>([])

	const searchLikeClick = () => {
		standbyList.value = echoSelectedList.value.filter(item => item.houseAddress.includes(searchLike.value || ''))
	}

	//已选中数据
	const selectedTable = ref<VxeGridInstance>()
	const selectedOption = reactive<VxeGridProps>({
		height: 'auto',
		size: 'medium',
		showOverflow: true,
		rowConfig: {
			isHover: true,
			keyField: 'id'
		},
		emptyText: '请在左侧选择房间',
		checkboxConfig: {
			trigger: 'row'
		},
		columns: [
			{
				width: 60,
				align: 'center',
				fixed: 'left',
				type: 'checkbox'
			},
			{
				title: '房源地址',
				minWidth: 400,
				align: 'left',
				field: 'houseAddress'
			},
			{
				title: '租金(元)',
				minWidth: 100,
				align: 'right',
				field: 'price'
			},
			{
				title: '押金(元)',
				minWidth: 100,
				align: 'right',
				field: 'deposit'
			}
		]
	})

	const getHouseList = () => {
		grid.value?.commitProxy('query')
	}
	const attrs = useAttrs()
	// 确认
	const submit = () => {
		if (!echoSelectedList.value.length) {
			return message.error('请先在左侧选择房间后提交')
		}

		emits('success', echoSelectedList.value)
		option.onCancel()
	}

	const getCheckeds = (): any[] => {
		return grid.value?.getCheckboxRecords().concat(grid.value.getCheckboxReserveRecords()) || []
	}

	const getRemoves = (): any[] => {
		return selectedTable.value?.getCheckboxRecords() || []
	}

	//选中
	const select = () => {
		const checkeds = getCheckeds()
		const res = validateFee(attrs.validateConfig,checkeds)
		if(!res) {
			return
		}
		echoSelectedList.value = checkeds.map(item => ({
			// 最低出租价格
			...item,
			basePrice: item.basePrice,
			houseAlias: item.houseAlias,
			houseId: item.houseId,
			housePid: item.housePid,
			houseRoomTypeName: item.houseRoomTypeName,
			houseRoomTypeDeposit: item.depositPrice,
			price: item.actualPrice,
			deposit: item.actualPrice,
			// 页面展示所需
			id: item.id,
			houseAddress: item.address,
			totalFloor: item.totalFloor,
			currentFloor: item.currentFloor,
			houseArea: item.houseArea,
			houseType: item.houseType,
			communityId: item.communityId,
			discountPrice: item.actualPrice
		}))

		searchLikeClick()
	}

	//移除
	const remove = () => {
		const removeIds = getRemoves().map(o => o.id) || []

		XEUtils.remove(echoSelectedList.value, item => removeIds.includes(item.id))

		const removeRows = getCheckeds().filter(item => removeIds.includes(item.id))
		// 同时取消左边表格的选中状态
		grid.value?.setCheckboxRow(removeRows, false)

		searchLike.value = null
		searchLikeClick()
	}

	watch(
		() => props.visible,
		() => {
			if (props.visible) {
				echoSelectedList.value = XEUtils.clone(props.roomSelected, true)
				searchLikeClick()
				if (houseListTableOption.checkboxConfig) {
					houseListTableOption.checkboxConfig.checkRowKeys = echoSelectedList.value.map(o => o.id)
				}
			}
		}
	)
</script>

<style lang="less">
	.select-house {
		.ant-modal-body {
			padding: 0 16px;
			overflow: auto;
			min-height: 600px;
			max-height: 1000px;
			height: calc(100vh - 200px);
			.margin-10 {
				margin: 10px 0;
			}
			.select-house-flex {
				display: flex;
				justify-content: space-between;
				height: 95%;
				.table-class {
					width: 45%;
				}
			}

			.button-group {
				text-align: center;
				display: flex;
				flex-direction: column;
				justify-content: center;
				.margin-bottom-20 {
					margin-bottom: 20px;
				}
			}
			.vxe-grid .vxe-grid--toolbar-wrapper,
			.vxe-table .vxe-grid--toolbar-wrapper {
				border: 0;
			}
		}
	}
</style>
